package com.company.cloud.admin.modules.user.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.company.cloud.admin.constant.PlatformAdminConstant;
import com.company.cloud.admin.constant.PlatformAdminErrorEnum;
import com.company.cloud.admin.modules.admin.controller.req.ManageUserLoginParam;
import com.company.cloud.admin.modules.base.entity.UserManageInfo;
import com.company.cloud.admin.modules.base.entity.UserRoleInfo;
import com.company.cloud.admin.modules.base.service.UserManageInfoService;
import com.company.cloud.admin.modules.base.service.UserRoleInfoService;
import com.company.cloud.admin.modules.cache.service.UserPermissionCacheService;
import com.company.cloud.captcha.modules.api.model.CaptchaVO;
import com.company.cloud.captcha.modules.service.CaptchaService;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.auth.annotation.Login;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.bean.LoginUserInfo;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.redis.service.RedisUtils;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.HttpContextUtils;
import com.company.cloud.common.utils.PasswordUtils;
import com.company.common.server.config.cloud.ProjectConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/admin/userlogin")
@Api(tags = "Admin_User_后管用户登陆")
public class ManageUserLoginController {

    @Value("${aj.captcha.type}")
    private static String captchaType;

    @Autowired
    private UserManageInfoService userManageInfoService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private UserRoleInfoService userRoleInfoService;

    @Autowired
    private UserPermissionCacheService userPermissionCacheService;

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private ProjectConfig projectConfig;

    @PostMapping("/login")
    @ApiOperation(value = "用户登陆", response = BaseResult.class)
    public BaseResult login(@RequestBody ManageUserLoginParam params) {
        ValidatorUtils.validate(params);
        //图形验证码
        captchaService.verification(this.getCaptcha2VO(params.getCaptchaVerification()));

        UserManageInfo userManageInfo = userManageInfoService.getOne(
                new QueryWrapper<UserManageInfo>().eq("user_name",params.getUserName()));
        if(userManageInfo==null){
            throw new BusinessException(PlatformAdminErrorEnum.USER_NULL);
        }
        if (!PlatformAdminConstant.AdminUserState.AUS_Open.getCode().equals(userManageInfo.getUserState())) {
            throw new BusinessException("1403", "用户不存在");
        }
        if (!PasswordUtils.isCorrect(params.getPassword(), userManageInfo.getSalt(), userManageInfo.getPassword())) {
            throw new BusinessException("1004", "密码错误");
        }
        List<UserRoleInfo> userRoleList = userRoleInfoService.list(new QueryWrapper<UserRoleInfo>()
                .eq("user_id",userManageInfo.getId()));
        String token =IdUtil.simpleUUID();
        LoginUserInfo cacheUser=this.getLoginUserInfo(userManageInfo,userRoleList,token);
        redisUtils.set(token, cacheUser);
        userPermissionCacheService.loadPermissionRoleCache(cacheUser);
        return BaseResult.ok(cacheUser);
    }

    @Login
    @PostMapping("/logout")
    @ApiOperation(value = "用户登出",response = BaseResult.class)
    public BaseResult logout() {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        if (redisUtils.hasKey(userInfo.getToken())) {
            redisUtils.delete(userInfo.getToken());
        }
        return BaseResult.ok();
    }


    /**二次验证CaptchaVO*/
    private  CaptchaVO getCaptcha2VO(String captchaVerification) {
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setCaptchaType(captchaType);
        captchaVO.setCaptchaVerification(captchaVerification);
        return captchaVO;
    }

    private LoginUserInfo getLoginUserInfo(UserManageInfo user, List<UserRoleInfo> userRoleList,String token) {
        LoginUserInfo loginUser=new LoginUserInfo();
        loginUser.setId(user.getId());
        loginUser.setCompanyNo("PT");
        loginUser.setUserName(user.getUserName());
        loginUser.setNickName(user.getNickName());
        loginUser.setHeadImg(user.getHeadImg());
        loginUser.setMobile(user.getMobile());
        loginUser.setToken(token);
        if(!CollectionUtils.isEmpty(userRoleList)){
            for (UserRoleInfo roleInfo:userRoleList){
                loginUser.addRoleCode(roleInfo.getRoleCode());
            }
        }
        return loginUser;
    }



}
